package com.tj.bo.trade.server.mq;

import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.tj.bo.common.conf.vo.MarketTimePrice;
import com.tj.bo.trade.client.ManipulateMarket;
import com.tj.bo.trade.client.enums.OrderStatusEnum;
import com.tj.bo.trade.server.dao.BinaryTradeDao;
import com.tj.bo.trade.server.dao.MockBinaryTradeDao;
import com.tj.bo.trade.server.entity.BinaryTradeEntity;
import com.tj.bo.trade.server.entity.MockBinaryTradeEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @program: binary-option
 * @description 结算交易
 * @author: binary
 * @create: 2020-06-16 16:35
 **/
//@RocketMQTag("manipulate_market")
@Service
public class ManipulateMarketConsumer implements ManipulateMarket {

    private static final Logger LOGGER = LoggerFactory.getLogger(ManipulateMarketConsumer.class);

    @Autowired
    private BinaryTradeDao binaryTradeDao;
    @Autowired
    private MockBinaryTradeDao mockBinaryTradeDao;
    @Autowired
    private RedisClient redisClient;

    public void onMessage(String tradeNo) {
        LOGGER.info("manipulate_market,接收到消息开始处理,tradeNo:{}", tradeNo);
        if (StringUtils.isEmpty(tradeNo)) {
            return;
        }

        BinaryTradeEntity binaryTradeEntity = binaryTradeDao.selectBinaryTradeByTradeNo(tradeNo);
        if (binaryTradeEntity == null) {
            LOGGER.warn("manipulate_market,订单不存在,tradeNo:{}", tradeNo);
            return;
        }
        Date date = new Date();
        //至少预留15秒
        if ((binaryTradeEntity.getExpectDeadline().getTime() - date.getTime()) / 1000 < 15) {
            LOGGER.warn("manipulate_market,至少预留15秒,tradeNo:{}", tradeNo);
            return;
        }
        if (!OrderStatusEnum.OPENING.getCode().equals(binaryTradeEntity.getOrderStatus())) {
            LOGGER.warn("manipulate_market,订单状态不匹配,tradeNo:{}", tradeNo);
            return;
        }
//        Set<ZSetOperations.TypedTuple<Object>> openingPriceSet = redisClient.zRangeByScoreWithScores(RedisKey.ZSET_BINARY_OPTION_PRODUCT_KEY, binaryTradeEntity.getOpeningTime().getTime(), date.getTime(), binaryTradeEntity.getProductCode());
//        List<MarketTimePrice> marketTimePriceList = Lists.newArrayList(openingPriceSet).stream().map(item -> {
//            MarketTimePrice marketTimePrice = JSON.parseObject((String) item.getValue(), MarketTimePrice.class);
//            return marketTimePrice;
//        }).collect(Collectors.toList());
//
//        LOGGER.info("manipulate_market,行情展示,tradeNo:{},marketTimePriceList:{}", tradeNo, JSON.toJSONString(marketTimePriceList));
//
//        MarketTimePrice chooseMarket = null;
//        //marketTimePriceList 是按时间正序排列的 所以valuableList也是正序
//        for (int i = marketTimePriceList.size() - 1; i >= 0; i--) {
//            MarketTimePrice marketTimePrice = marketTimePriceList.get(i);
//            BigDecimal price = new BigDecimal(marketTimePrice.getMarketPrice());
//            if (binaryTradeEntity.getTrendType() == 0 && price.compareTo(binaryTradeEntity.getOpeningPrice()) > 0) {
//                chooseMarket = marketTimePrice;
//                break;
//            }
//            if (binaryTradeEntity.getTrendType() == 1 && price.compareTo(binaryTradeEntity.getOpeningPrice()) < 0) {
//                chooseMarket = marketTimePrice;
//                break;
//            }
//        }
//        if (chooseMarket == null) {
//            for (int i = marketTimePriceList.size() - 1; i >= 0; i--) {
//                MarketTimePrice marketTimePrice = marketTimePriceList.get(i);
//                BigDecimal price = new BigDecimal(marketTimePrice.getMarketPrice());
//                if (binaryTradeEntity.getTrendType() == 0 && price.compareTo(binaryTradeEntity.getOpeningPrice()) >= 0) {
//                    chooseMarket = marketTimePrice;
//                    break;
//                }
//                if (binaryTradeEntity.getTrendType() == 1 && price.compareTo(binaryTradeEntity.getOpeningPrice()) <= 0) {
//                    chooseMarket = marketTimePrice;
//                    break;
//                }
//            }
//        }
//        if (chooseMarket == null) {
//            LOGGER.warn("1分钟内不存在选举值无法操作,tradeNo:{}", tradeNo);
//            return;
//        }
//        LOGGER.info("manipulate_market,选举数据成功,tradeNo:{},chooseMarket:{}", tradeNo, JSON.toJSONString(chooseMarket));
//        BigDecimal chooseMarketPrice = new BigDecimal(chooseMarket.getMarketPrice());
//        ProductEnum productEnum = ProductEnum.getEnumByProductCode(binaryTradeEntity.getProductCode());
//        if (productEnum != null) {
//            chooseMarketPrice = chooseMarketPrice.setScale(productEnum.getTailNum(), BigDecimal.ROUND_HALF_UP);
//        }

        MockBinaryTradeEntity mockBinaryTradeEntity = new MockBinaryTradeEntity();
        BeanUtils.copyProperties(binaryTradeEntity, mockBinaryTradeEntity);
        mockBinaryTradeEntity.setClosingPrice(null);
        mockBinaryTradeEntity.setId(null);
        mockBinaryTradeDao.insert(mockBinaryTradeEntity);
    }

    private BigDecimal checkAndChooseData(List<MarketTimePrice> valuableList) {
        if (CollectionUtils.isEmpty(valuableList)) {
            return null;
        }
        return new BigDecimal(valuableList.get(valuableList.size() - 1).getMarketPrice());
    }

    @Override
    public void solve(String tradeNo) {
        this.onMessage(tradeNo);
    }
}
